# -*- coding:utf-8 -*-
import hashlib, random
from . import db, memc, mem_hash

TYPE_COMMON = 0
TYPE_CHIEF = 1 # 段长
TYPE_ADMIN = 2 # 管理员

def addUser(username, password, nickname, companyId = 0, _type = TYPE_COMMON):
    salt = ''.join(random.sample('zyxwvutsrqponmlkjihgfedcba0123456789', 6))
    password = hashlib.md5(hashlib.md5(password).hexdigest() + salt).hexdigest()
    return db.insert('user', username = username , password = password, nickname = nickname, salt = salt, company_id = companyId, type = _type)

def getUserByNamePass(username, password):
    user = getUserByUsername(username)
    if user:
        if user.password == hashlib.md5(hashlib.md5(password).hexdigest() + user.salt).hexdigest():
            return user
        return 0
    return None

def getUserByUsername(username):
    result = memc.get(mem_hash('user%s' % username))
    if not result:
        result = db.query('SELECT * FROM user WHERE username = $username', locals())
        if result:
            value = result[0]
            memc.set(mem_hash('user%s' % username), value, time = 60 * 4)
            return value
        return None
    return result

def getById(userId):
    result = db.query('SELECT * FROM user WHERE id = $userId', locals())
    if result:
        return result[0]
    return None

def deleteById(userId):
    return db.delete('user', 'id = $userId', vars = locals())

def clear():
    db.query('delete from user')